'''
    @project: Masdevallia
    @author: Austin Baker
    @created: 2/22/2014
    @license: http://opensource.org/licenses/mit-license.php

    The MIT License (MIT)

    Copyright (c) 2014 Austin Baker
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    
    ------
    
    About: Build modules widget used in the Rig Tools window.
'''

'''
============================================================
--->>   IMPORT MODULES
============================================================
'''
import os

import masdevallia.settings.PathConstants as PathConstants
import masdevallia.utility.FileSystem as FileSystem
import masdevallia.utility.WindowUtility as WinUtility
import masdevallia.windows.ModuleInfoTile as ModuleInfoTile
import masdevallia.utility.RigControls as RigControls
import masdevallia.utility.XML as XML

from PySide import QtCore
from PySide import QtGui


'''
============================================================
--->>   GLOBAL VARIABLES
============================================================
'''
form_class, base_class = WinUtility.loadUiType( PathConstants.WIDGET_BUILD_MODULES_GUI )

'''
============================================================
--->>   BUILD MODULES CLASS
============================================================
'''
class BuildModules( form_class, base_class ):
    def __init__( self, parent=None ):
        super( BuildModules, self).__init__( parent )
        self.setupUi( self )
        self.setObjectName( 'Build_Modules_Widget' )
        
        # List containing InfoTiles.
        self.head_widgets = []
        self.torso_widgets = []
        self.arms_widgets = []
        self.legs_widgets = []
        self.hands_widgets = []
        self.feet_widgets = []
        self.root_widgets = []
        
        self.initUI()
    
    def initUI( self ):        
        # Set each tab's QFrame background to black. These frames are defined in
        # the UI file.
        
        self.head_layout.setAlignment( QtCore.Qt.AlignTop )
        self.torso_layout.setAlignment( QtCore.Qt.AlignTop )
        self.arms_layout.setAlignment( QtCore.Qt.AlignTop )
        self.legs_layout.setAlignment( QtCore.Qt.AlignTop )
        self.hands_layout.setAlignment( QtCore.Qt.AlignTop )
        self.feet_layout.setAlignment( QtCore.Qt.AlignTop )
        self.root_layout.setAlignment( QtCore.Qt.AlignTop )
        
        CSS_FRAME = '''
            QFrame {
                background-color: black;
            }'''
        self.head_frame.setStyleSheet( CSS_FRAME )
        self.torso_frame.setStyleSheet( CSS_FRAME )
        self.arms_frame.setStyleSheet( CSS_FRAME )
        self.legs_frame.setStyleSheet( CSS_FRAME )
        self.hands_frame.setStyleSheet( CSS_FRAME )
        self.feet_frame.setStyleSheet( CSS_FRAME )
        self.root_frame.setStyleSheet( CSS_FRAME )
        
        # Refresh the tiles on all tabs.
        self.refreshInfoTiles()
        
        # Do the connections.
        self.connections()
        
    def connections( self ):
        self.tab_widget.currentChanged.connect( self.refreshInfoTiles )
                
    def saveSelectedToXML( self ):
        RigControls.saveSelectedToXML()
        
    def refreshInfoTiles( self ):
        # Fill the GUI with Info Tiles
        if self.tab_widget.currentIndex() == 0:# head
            directory = PathConstants.PATH_MODULES_HEADS
            WinUtility.clearLayout( self.head_layout )
            self.rootWidgets = []
            
        elif self.tab_widget.currentIndex() == 1:# torso
            directory = PathConstants.PATH_MODULES_TORSOS
            WinUtility.clearLayout( self.torso_layout )
            self.jointWidgets = []
            
        elif self.tab_widget.currentIndex() == 2:# arms
            directory = PathConstants.PATH_MODULES_ARMS
            WinUtility.clearLayout( self.arms_layout )
            self.spacerWidgets = []
             
        elif self.tab_widget.currentIndex() == 3:# legs
            directory = PathConstants.PATH_MODULES_LEGS
            WinUtility.clearLayout( self.legs_layout )
            self.controlWidgets = []
            
        elif self.tab_widget.currentIndex() == 4:# hands
            directory = PathConstants.PATH_MODULES_HANDS
            WinUtility.clearLayout( self.hands_layout )
            self.controlWidgets = [] 
            
        elif self.tab_widget.currentIndex() == 5:# feet
            directory = PathConstants.PATH_MODULES_FEET
            WinUtility.clearLayout( self.feet_layout )
            self.controlWidgets = [] 
            
        elif self.tab_widget.currentIndex() == 6:# root
            directory = PathConstants.PATH_MODULES_ROOTS
            WinUtility.clearLayout( self.root_layout )
            self.controlWidgets = [] 
        
        # Get the controls XML files.
        files = FileSystem.searchSubDir( directory, 'xml' )        
        
        for key in files.keys():
            for f in files[key]:
                file_path = os.path.join( key, f )
                
                if os.path.exists( file_path ):
                    xml_data = XML.XML().readFile( inFilename=file_path )
            
                    if xml_data is not None:
                        for xml_object in xml_data.objects:
                            module_name = None
                            module_import_path = None
                            module_icon = None                            
                            
                            if xml_object.name is not None:
                                module_name = xml_object.name
                            
                            if xml_object.type is not None:
                                module_import_path = xml_object.type
                            
                            if xml_object.icon is not None:
                                module_icon = xml_object.icon
 
                            # Create the widget.
                            tile = ModuleInfoTile.ModuleInfoTile( module_name = module_name,
                                                                  module_import_path = module_import_path,
                                                                  module_icon = module_icon )               
                            
                            # Add the widgets to the correct layout.
                            if self.tab_widget.currentIndex() == 0:# heads
                                self.head_widgets.append( tile )
                                self.head_layout.addWidget( self.head_widgets[-1] )
                                
                            elif self.tab_widget.currentIndex() == 1:# torsos
                                self.torso_widgets.append( tile )
                                self.torso_layout.addWidget( self.torso_widgets[-1] )
                                
                            elif self.tab_widget.currentIndex() == 2:# arms
                                self.arms_widgets.append( tile )
                                self.arms_layout.addWidget( self.arms_widgets[-1] )
                                
                            elif self.tab_widget.currentIndex() == 3:# legs
                                self.legs_widgets.append( tile ) 
                                self.legs_layout.addWidget( self.legs_widgets[-1] )
                                
                            elif self.tab_widget.currentIndex() == 4:# hands
                                self.hands_widgets.append( tile ) 
                                self.hands_layout.addWidget( self.hands_widgets[-1] )
                                
                            elif self.tab_widget.currentIndex() == 5:# feet
                                self.feet_widgets.append( tile ) 
                                self.feet_layout.addWidget( self.feet_widgets[-1] )
                                
                            elif self.tab_widget.currentIndex() == 6:# root
                                self.root_widgets.append( tile ) 
                                self.root_layout.addWidget( self.root_widgets[-1] )